package com.juzhencms.apps.busi.web;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;
import com.juzhencms.apps.busi.entity.AdminLoginUser;
import com.juzhencms.apps.busi.service.AppWeixinSourceService;
import com.juzhencms.apps.common.interceptor.UserInterceptor;
import com.juzhencms.apps.common.tread.TreadTasks;

import lombok.extern.slf4j.Slf4j;


@Controller
@RequestMapping("/dataHistory")
@Slf4j
public class DataHistoryController  extends BaseController{
	
	@Autowired
	private AppWeixinSourceService appWeixinSourceService;
	
	@Autowired
	private TreadTasks treadTasks;
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="where 1 ";
		
		if(request.getParameter("data_type")!=null && request.getParameter("data_id")!=null){
			where+=" and data_type = ? and data_id=? ";
			whereParamList.add(request.getParameter("data_type"));
			whereParamList.add(request.getParameter("data_id"));
		}else {
			where+=" and 1=0 ";
		}
		
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		//排序参数 
		String sortField="create_time";
		String sortOrder="desc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,user_type,user_id,user_account,user_name,check_status,create_time,update_description from "+DBTable.dataHistory+" "+where+" order by "+sortField+" "+sortOrder+",id desc limit ?,?", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				if(row.get("create_time")!=null) {
					Date date = (Date)row.get("create_time");
					row.put("create_time",sdf.format(date));
				}
			}
			this.getDictionaryService().setDictionaryText(dataList, "check_status", this.getDictionaryService().getDictionaryItemList("checkStatusVars"));
			
			
		}
		
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.dataHistory+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		
		
		
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.dataHistory+" where id=?",new Object[]{id});	

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date)record.get("create_time");
		record.put("create_time",sdf.format(date) );
		data.put("data", record);
		
		return WebUtil.resultString(data,request);
	}
	
	/*@RequestMapping(value="/detailWindow/{id}",produces="text/html; charset=UTF-8")
	public String detailWindow(@PathVariable("id") String id,Map<String,Object> model,HttpServletRequest request){
		
		AdminLoginUser loginUser=this.getLoginUser();
		
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.dataHistory+" where id=?",new Object[]{id});	
		
		if(record==null) {
			return "";
		}
		
		//格式化时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date)record.get("create_time");
		record.put("create_time",sdf.format(date) );
		
		//设置状态字段
		this.getDictionaryService().setDictionaryText(record, "check_status", this.getDictionaryService().getDictionaryItemList("checkStatusVars"));
		

		//还原数据字段
		String dataJson=record.get("params").toString();
		Map params=JSON.parseObject(dataJson,Map.class);

		model.put("data", params);
		record.remove("params");
		
		//关联的栏目
		int menuId=0;
		if(record.get("menu_id")!=null) {
			
			menuId=Integer.parseInt(record.get("menu_id").toString());
			
			//查询栏目及站点信息
			Map menu=this.getCommonService().getJdbcDao().queryRow("select id,name,module,site_id from "+DBTable.menu+" where id=?", new Object[] {menuId});
			if(menu!=null) {
				model.put("menu", menu);
				Map site=this.getCommonService().getJdbcDao().queryRow("select id,name,domain from "+DBTable.site+" where id=?", new Object[] {menu.get("site_id")});
				model.put("site", site);
			}
		}
		Map external_params=null;
		if(record.get("external_params")!=null && !record.get("external_params").toString().equals("")) {
			external_params=JSON.parseObject(record.get("external_params").toString(),Map.class);
			model.put("external_params", external_params);
			record.remove("external_params");
		}
		
		//根据数据类型确定栏目模块、编辑链接、数据字段
		String moduleName=record.get("module_name").toString();
		if(record.get("data_type").toString().equals(DBTable.news)) {
			
			model.put("edit_link", "#/newsLibForm/"+record.get("data_id"));
			
			if(params!=null && params.get("image")!=null && !params.get("image").equals("")) {
				params.put("image", Config.getUploadUrlPath()+"/"+params.get("image"));
			}
			if(params!=null && params.get("video")!=null && !params.get("video").equals("")) {
				params.put("video", Config.getUploadUrlPath()+"/"+params.get("video"));
			}
			
			if(params!=null && params.get("share")!=null && !params.get("share").equals("")) {
				params.put("share", this.getDictionaryService().getDictionaryItem("boolVars", params.get("share").toString()).get("text"));
			}
			
			//为了兼容oss图片，显示oss图片链接时增加后缀?x-oss-process=image/auto-orient,1/quality,q_90
			if(external_params!=null && external_params.get("uncheckImgs")!=null) {
				
				List imgList=(List)external_params.get("uncheckImgs");
				
				//log.info(JSON.toJSONString(imgList));
				
				List imgList2=new ArrayList();
				if(imgList!=null && imgList.size()>0) {
					for(int i=0;i<imgList.size();i++) {
						String img=imgList.get(i).toString();
						if(img.indexOf("?")<0) {
							img=img+"?x-oss-process=image/auto-orient,1/quality,q_90";
						}
						imgList2.add(img);
					}
				}
				external_params.put("uncheckImgs", imgList2);
			}
			
			//params.put("create_time",sdf.format((Date)params.get("create_time")) );
			
		}else if(record.get("data_type").toString().equals(DBTable.article)){
			
			model.put("edit_link", "#/"+menuId+".article");
			
			if(params!=null && params.get("image")!=null && !params.get("image").equals("")) {
				params.put("image", Config.getUploadUrlPath()+"/"+params.get("image"));
			}
			if(params!=null && params.get("video")!=null && !params.get("video").equals("")) {
				params.put("video", Config.getUploadUrlPath()+"/"+params.get("video"));
			}
			
		}else if(record.get("data_type").toString().equals(DBTable.appResource)){
			
			model.put("edit_link", "#/appResourceForm/"+record.get("data_id"));
			
			
			
			
		}else if(record.get("data_type").toString().equals(DBTable.templateFile)){
			
			moduleName="templateFile";
			
			
			
		}
		model.put("moduleName", moduleName);
		
		//如果当前版本审核通过并且还有更新的版本数据，允许执行恢复
		if(record.get("check_status").toString().equals("1")) {
			Map newRecord=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.dataHistory+" where data_type=? and data_id=? and id>? order by id desc limit 0,1",new Object[]{record.get("data_type"),record.get("data_id"),id});	
			if(newRecord!=null) {
				model.put("can_restore", true);
			}
		}
		
		
		
		
		
		model.put("record", record);
		//查询最新的一条审批记录
		Map checkRecord=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRecord+" where data_history_id=? order by create_time desc limit 0,1", new Object[] {record.get("id")});
		if(checkRecord!=null) {
			model.put("checkRecord", checkRecord);
			//如果当前状态是未审核
			if(record.get("check_status").toString().equals("0")) {
				//看当前用户是否具备审批权限
				int checkRoleId=Integer.parseInt(checkRecord.get("check_role_id").toString());
				if(loginUser.getRoleIdList().contains(checkRoleId)) {
					model.put("can_check", true);
				}	
				
			}
		}
		
		//判断当前用户是否具备编辑权限
		Map permissions=loginUser.getPermissions();
		if(permissions!=null) {
			String permissionModuleName=moduleName;
			if(menuId>0) {
				permissionModuleName=menuId+"."+permissionModuleName;
			}
			if(permissions.get("root")!=null || permissions.get(permissionModuleName)!=null) {
				model.put("can_edit", true);
				
				
				
			}
		}
		return "dataHistoryDetail";
	}*/
	
	@RequestMapping(value="/detailWindowData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailWindowData(@PathVariable("id") String id,Map<String,Object> model,HttpServletRequest request){
		
		AdminLoginUser loginUser=this.getLoginUser();
		
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.dataHistory+" where id=?",new Object[]{id});	
		
		
		
		if(record==null) {
			return WebUtil.resultString(null,request);
		}
		
		//格式化时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date)record.get("create_time");
		record.put("create_time",sdf.format(date) );
		
		//设置状态字段，使用版本记录的审核状态显示在页面，不依赖审批记录的状态（因为审批记录可能存在多个状态不一致的）
		this.getDictionaryService().setDictionaryText(record, "check_status", this.getDictionaryService().getDictionaryItemList("checkStatusVars"));
		

		//还原数据字段
		String dataJson=record.get("params").toString();
		Map params=JSON.parseObject(dataJson,Map.class);

		model.put("data", params);
		record.remove("params");
		
		//关联的栏目
		int menuId=0;
		if(record.get("menu_id")!=null) {
			
			menuId=Integer.parseInt(record.get("menu_id").toString());
			
			//查询栏目及站点信息
			Map menu=this.getCommonService().getJdbcDao().queryRow("select id,name,module,site_id from "+DBTable.menu+" where id=?", new Object[] {menuId});
			if(menu!=null) {
				model.put("menu", menu);
				Map site=this.getCommonService().getJdbcDao().queryRow("select id,name,domain from "+DBTable.site+" where id=?", new Object[] {menu.get("site_id")});
				model.put("site", site);
			}
		}
		Map external_params=null;
		if(record.get("external_params")!=null && !record.get("external_params").toString().equals("")) {
			external_params=JSON.parseObject(record.get("external_params").toString(),Map.class);
			model.put("external_params", external_params);
			record.remove("external_params");
		}
		
		//根据数据类型确定栏目模块、编辑链接、数据字段
		String moduleName=record.get("module_name").toString();
		if(record.get("data_type").toString().equals(DBTable.news)) {
			
			model.put("edit_link", "/newsLibForm/"+record.get("data_id"));
			
			if(params!=null && params.get("image")!=null && !params.get("image").equals("")) {
				params.put("image", Config.getUploadUrlPath()+"/"+params.get("image"));
			}
			if(params!=null && params.get("video")!=null && !params.get("video").equals("")) {
				params.put("video", Config.getUploadUrlPath()+"/"+params.get("video"));
			}
			
			if(params!=null && params.get("share")!=null && !params.get("share").equals("")) {
				params.put("share", this.getDictionaryService().getDictionaryItem("boolVars", params.get("share").toString()).get("text"));
			}
			
			//获取版权来源显示的文本
			String copyrightFontText="";
			if(params.get("copyright_font")!=null) {
				copyrightFontText=this.getDictionaryService().getCheckBoxText(this.getDictionaryService().getDictionaryItemList("copyrightFontVars"), params.get("copyright_font").toString());
			}
			params.put("copyright_font", copyrightFontText);
			
			String copyrightImageText="";
			if(params.get("copyright_image")!=null) {
				copyrightImageText=this.getDictionaryService().getCheckBoxText(this.getDictionaryService().getDictionaryItemList("copyrightImageVars"), params.get("copyright_image").toString());
			}
			params.put("copyright_image", copyrightImageText);
			
			String copyrightProductText="";
			if(params.get("copyright_product")!=null) {
				copyrightProductText=this.getDictionaryService().getCheckBoxText(this.getDictionaryService().getDictionaryItemList("copyrightProductVars"), params.get("copyright_product").toString());
			}
			params.put("copyright_product", copyrightProductText);
			
			String copyrightContentText="";
			if(params.get("copyright_content")!=null) {
				copyrightContentText=this.getDictionaryService().getCheckBoxText(this.getDictionaryService().getDictionaryItemList("copyrightContentVars"), params.get("copyright_content").toString());
			}
			//params.put("copyright_content", copyrightContentText);
			if(params.get("copyright_content_other")!=null && !params.get("copyright_content_other").toString().equals("")) {
				if(copyrightContentText.equals("")) {
					copyrightContentText=params.get("copyright_content_other").toString();
				}else {
					copyrightContentText+=","+params.get("copyright_content_other").toString();
				}
			}
			params.put("copyright_content", copyrightContentText);
			
			String copyrightDoctorText="";
			if(params.get("copyright_doctor")!=null) {
				copyrightDoctorText=this.getDictionaryService().getCheckBoxText(this.getDictionaryService().getDictionaryItemList("copyrightDoctorVars"), params.get("copyright_doctor").toString());
			}
			params.put("copyright_doctor", copyrightDoctorText);
			
			//为了兼容oss图片，显示oss图片链接时增加后缀?x-oss-process=image/auto-orient,1/quality,q_90
			if(external_params!=null && external_params.get("uncheckImgs")!=null) {
				
				List imgList=(List)external_params.get("uncheckImgs");
				
				//log.info(JSON.toJSONString(imgList));
				
				List imgList2=new ArrayList();
				if(imgList!=null && imgList.size()>0) {
					for(int i=0;i<imgList.size();i++) {
						String img=imgList.get(i).toString();
						if(img.indexOf("?")<0) {
							img=img+"?x-oss-process=image/auto-orient,1/quality,q_90";
						}
						imgList2.add(img);
					}
				}
				external_params.put("uncheckImgs", imgList2);
			}
			
			//params.put("create_time",sdf.format((Date)params.get("create_time")) );
			
		}else if(record.get("data_type").toString().equals(DBTable.article)){
			
			model.put("edit_link", "/"+menuId+".article");
			
			if(params!=null && params.get("image")!=null && !params.get("image").equals("")) {
				params.put("image", Config.getUploadUrlPath()+"/"+params.get("image"));
			}
			if(params!=null && params.get("video")!=null && !params.get("video").equals("")) {
				params.put("video", Config.getUploadUrlPath()+"/"+params.get("video"));
			}
			
		}else if(record.get("data_type").toString().equals(DBTable.appResource)){
			
			model.put("edit_link", "/appResourceForm/"+record.get("data_id"));
			
			//获取版权来源显示的文本
			//获取版权来源显示的文本
			String copyrightFontText="";
			if(params.get("copyright_font")!=null) {
				copyrightFontText=this.getDictionaryService().getCheckBoxText(this.getDictionaryService().getDictionaryItemList("copyrightFontVars"), params.get("copyright_font").toString());
			}
			params.put("copyright_font", copyrightFontText);
			
			String copyrightImageText="";
			if(params.get("copyright_image")!=null) {
				copyrightImageText=this.getDictionaryService().getCheckBoxText(this.getDictionaryService().getDictionaryItemList("copyrightImageVars"), params.get("copyright_image").toString());
			}
			params.put("copyright_image", copyrightImageText);
			
			String copyrightProductText="";
			if(params.get("copyright_product")!=null) {
				copyrightProductText=this.getDictionaryService().getCheckBoxText(this.getDictionaryService().getDictionaryItemList("copyrightProductVars"), params.get("copyright_product").toString());
			}
			params.put("copyright_product", copyrightProductText);
			
			String copyrightContentText="";
			if(params.get("copyright_content")!=null) {
				copyrightContentText=this.getDictionaryService().getCheckBoxText(this.getDictionaryService().getDictionaryItemList("copyrightContentVars"), params.get("copyright_content").toString());
			}
			//params.put("copyright_content", copyrightContentText);
			if(params.get("copyright_content_other")!=null && !params.get("copyright_content_other").toString().equals("")) {
				if(copyrightContentText.equals("")) {
					copyrightContentText=params.get("copyright_content_other").toString();
				}else {
					copyrightContentText+=","+params.get("copyright_content_other").toString();
				}
			}
			params.put("copyright_content", copyrightContentText);
			
			String copyrightDoctorText="";
			if(params.get("copyright_doctor")!=null) {
				copyrightDoctorText=this.getDictionaryService().getCheckBoxText(this.getDictionaryService().getDictionaryItemList("copyrightDoctorVars"), params.get("copyright_doctor").toString());
			}
			params.put("copyright_doctor", copyrightDoctorText);
			
		}else if(record.get("data_type").toString().equals(DBTable.templateFile)){
			
			moduleName="templateFile";
			
			
			
		}
		model.put("moduleName", moduleName);
		
		/*//如果当前版本审核通过并且还有更新的版本数据，允许执行恢复，恢复功能暂未开启
		if(record.get("check_status").toString().equals("1")) {
			Map newRecord=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.dataHistory+" where data_type=? and data_id=? and id>? order by id desc limit 0,1",new Object[]{record.get("data_type"),record.get("data_id"),id});	
			if(newRecord!=null) {
				model.put("can_restore", true);
			}
		}*/
		
		
		
		
		
		model.put("record", record);
		//存放返回审批记录的变量，审批记录用于前台进行审批操作
		Map checkRecord=null;
		//如果传入了审核记录ID，则直接采用，否则读取本角色可参与审批的最新一条审批记录
		if(request.getParameter("checkRecordId")!=null && !request.getParameter("checkRecordId").equals("")){
			checkRecord=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRecord+" where id=? ", new Object[] {request.getParameter("checkRecordId")});
		}else {
			//查询本用户角色可审批的最早一条审批记录
			String rolesIdStr=org.apache.commons.lang3.StringUtils.join(loginUser.getRoleIdList().toArray(), ",");
			if(rolesIdStr==null || rolesIdStr.equals("")) {
				rolesIdStr="0";
			}
			checkRecord=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRecord+" where data_history_id=? and check_status=0 and check_role_id in("+rolesIdStr+") order by id asc limit 0,1", new Object[] {record.get("id")});

			
			//如果查询不到，就查询最早的一条待审批记录
			//checkRecord=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRecord+" where data_history_id=? order by create_time desc limit 0,1", new Object[] {record.get("id")});
			
			//如果查不到，就查询最后一条审批记录
		}
		
		
		
		
		
		if(checkRecord!=null) {
			model.put("checkRecord", checkRecord);
			//如果当前状态是未审核
			if(checkRecord.get("check_status").toString().equals("0")) {
				//看当前用户是否具备审批权限
				int checkRoleId=Integer.parseInt(checkRecord.get("check_role_id").toString());
				if(loginUser.getRoleIdList().contains(checkRoleId)) {
					model.put("can_check", true);
					
					//如果可以审批，查询对应的审批规则节点
					Map checkRuleItem=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRuleItem+" where id=? and del_flag=0", new Object[] {checkRecord.get("check_rule_item_id")});
					model.put("checkRuleItem", checkRuleItem);
				}	
				
			}
		}
		
		//判断当前用户是否具备编辑权限
		Map permissions=loginUser.getPermissions();
		
		//log.info(JSON.toJSONString(permissions));
		
		
		if(permissions!=null) {
			String permissionModuleName=moduleName;
			if(menuId>0) {
				permissionModuleName=menuId+"."+permissionModuleName;
			}
			//log.info(permissionModuleName);
			if(permissions.get("root")!=null || permissions.get(permissionModuleName)!=null) {
				model.put("can_edit", true);
				
				
				
			}
		}
		//return "dataHistoryDetail";
		//Map result=new HashMap();
		//result.put("data", model);
		model.put("content", this.templateResult("dataHistoryDetailData", model));
		return WebUtil.resultString(model,request);
		//return this.templateResult("dataHistoryDetailData", model);
		
	}
	
	@RequestMapping(value="/checkData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String checkData(HttpServletRequest request){
		Date now=new Date();
		
		//参数校验
		String id=request.getParameter("id");
		String check_status=request.getParameter("check_status");
		String check_description=request.getParameter("check_description");
		String extParam=request.getParameter("extParam");
		if(id!=null && !id.equals("") && check_status!=null && !check_status.equals("")) {
			//查询审批内容
			Map thisCheckRecord=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRecord+" where id=? and check_status=0 and del_flag=0", new Object[] {id});
			
			if(thisCheckRecord==null) {
				Map result=new HashMap();
				result.put("result", 0);
				result.put("msg", "没有找到需要审批的数据，请刷新后重试");
				return WebUtil.resultString(result,request);
			}
			
			AdminLoginUser loginUser=this.getLoginUser();
			//判断当前用户有无审批权限
			int checkRoleId=Integer.parseInt(thisCheckRecord.get("check_role_id").toString());
			if(!loginUser.getRoleIdList().contains(checkRoleId)) {
				Map result=new HashMap();
				result.put("result", 0);
				result.put("msg", "没有审批权限");
				return WebUtil.resultString(result,request);
			}
			
			if(!check_status.equals("1") && !check_status.equals("2") && !check_status.equals("3") && !check_status.equals("4") && !check_status.equals("5") && !check_status.equals("6")) {
				Map result=new HashMap();
				result.put("result", 0);
				result.put("msg", "操作有误");
				return WebUtil.resultString(result,request);
			}
			
			//提前定义好流转规则
			Map moveRule=null;
			List moveRuleItems=new ArrayList();
			if(check_status.equals("5")) {//流转
				if(extParam==null || extParam.equals("")) {
					Map result=new HashMap();
					result.put("result", 0);
					result.put("msg", "参数有误");
					return WebUtil.resultString(result,request);
				}
				
				//校验转发的规则在限定的转发范围内
				Map checkRuleItem=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRuleItem+" where id=? ", new Object[] {thisCheckRecord.get("check_rule_item_id")});
				if(checkRuleItem==null || checkRuleItem.get("move_rules")==null || checkRuleItem.get("move_rules").toString().equals("")) {
					Map result=new HashMap();
					result.put("result", 0);
					result.put("msg", "未找到转发规则");
					return WebUtil.resultString(result,request);
				}
				
				
				List moveRuleIdList = java.util.Arrays.asList(checkRuleItem.get("move_rules").toString().split(","));
				if(!moveRuleIdList.contains(extParam)) {
					Map result=new HashMap();
					result.put("result", 0);
					result.put("msg", "转发规则不匹配");
					return WebUtil.resultString(result,request);
				}
				
				
				int moveRuleId=Integer.parseInt(extParam);
				
				
				//校验转发规则是否存在
				moveRule=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRule+" where id=? and del_flag=0", new Object[] {moveRuleId});
				if(moveRule==null) {
					Map result=new HashMap();
					result.put("result", 0);
					result.put("msg", "转发规则不存在");
					return WebUtil.resultString(result,request);
				}
				//moveRuleItem=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRuleItem+" where check_rule_id=? and publish=1 and del_flag=0 order by position asc limit 0,1", new Object[] {moveRuleId});
				moveRuleItems=this.getDataHistoryService().getNextCheckRuleItems(moveRuleId, null);
				if(moveRuleItems.size()==0) {
					Map result=new HashMap();
					result.put("result", 0);
					result.put("msg", "转发规则不符合要求，请先定义规则明细");
					return WebUtil.resultString(result,request);
				}
				
			}else if(check_status.equals("6")) {//会签
				if(extParam==null || extParam.equals("")) {
					Map result=new HashMap();
					result.put("result", 0);
					result.put("msg", "参数有误");
					return WebUtil.resultString(result,request);
				}
				
				//要会签的角色清单
				Map extParamMap=JSON.parseObject(extParam,Map.class);
				List roleIdList=java.util.Arrays.asList(extParamMap.get("check_roles").toString().split(","));
				String roleIds="0";
				for(int i=0;i<roleIdList.size();i++) {
					String tmpid=roleIdList.get(i).toString();
					if(tmpid!=null && !tmpid.equals("")) {
						roleIds+=","+tmpid;
					}
				}
				List roleList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.role+" where id in ("+roleIds+") and publish=1 and del_flag=0 limit 0,1000");
				if(roleList==null || roleList.size()==0) {
					Map result=new HashMap();
					result.put("result", 0);
					result.put("msg", "参数有误");
					return WebUtil.resultString(result,request);
				}
				
				//获取是否允许上传文件
				int allowUploadImg=0;
				if((boolean)extParamMap.get("allow_upload_img")) {
					allowUploadImg=1;
				}
				//获取是否发送短信
				int openMobileNotice=0;
				if((boolean)extParamMap.get("open_mobile_notice")) {
					openMobileNotice=1;
				}
				//获取是否发送微信消息
				int openWeixinNotice=0;
				if((boolean)extParamMap.get("open_weixin_notice")) {
					openWeixinNotice=1;
				}
				
				//查询原有的审批记录以获取用户通知设置
				Map oldCheckRule=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRule+" where id=?",new Object[] {thisCheckRecord.get("check_rule_id")});
				//查询当前审批流程节点以配置流转及通知信息
				Map oldCheckRuleItem=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRuleItem+" where id=?", new Object[] {thisCheckRecord.get("check_rule_item_id")});
				//查询后续节点并复制流程
				List oldCheckRuleOtherItems=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.checkRuleItem+" where check_rule_id=? and id!=? and position>=?", new Object[] {oldCheckRuleItem.get("check_rule_id"),oldCheckRuleItem.get("id"),oldCheckRuleItem.get("position")});
				
				
				
				//临时排序字段，使用时++操作
				long position=now.getTime();
				
				//创建审批流程
				Map newTempCheckRule=new HashMap();
				newTempCheckRule.put("name", "审批记录"+thisCheckRecord.get("id")+"的临时会签流程");
				newTempCheckRule.put("org_id", this.getLoginUser().getOrgId());
				newTempCheckRule.put("org_name", this.getLoginUser().getOrgName());
				newTempCheckRule.put("type", 1);//临时流程，不会在后台管理中显示
				newTempCheckRule.put("publish", 1);
				newTempCheckRule.put("position", position++);
				newTempCheckRule.put("open_mobile_notice", oldCheckRule.get("open_mobile_notice"));//和原流程的用户通知状态一致
				newTempCheckRule.put("open_weixin_notice", oldCheckRule.get("open_weixin_notice"));//和原流程的用户通知状态一致
				newTempCheckRule.put("create_user", this.getLoginUser().getId());
				newTempCheckRule.put("create_time", now);
				newTempCheckRule.put("update_user", this.getLoginUser().getId());
				newTempCheckRule.put("update_time", now);
				int newTempCheckRuleId=this.getCommonService().getJdbcDao().addObj(DBTable.checkRule, newTempCheckRule);
				newTempCheckRule.put("id", newTempCheckRuleId);
				//将新创建的流程设置为流转流程
				moveRule=newTempCheckRule;
				
				//创建流程节点
				for(int i=0;i<roleList.size();i++) {
					Map tmpRole=(Map)roleList.get(i);
					Map newTempCheckRuleItem=new HashMap();
					newTempCheckRuleItem.put("check_rule_id", newTempCheckRuleId);
					newTempCheckRuleItem.put("type", 1);//类型为批注
					newTempCheckRuleItem.put("asyn", 1);//允许同时进行批注
					newTempCheckRuleItem.put("org_id", tmpRole.get("org_id"));
					newTempCheckRuleItem.put("org_name", tmpRole.get("org_name"));
					newTempCheckRuleItem.put("role_id", tmpRole.get("id"));
					newTempCheckRuleItem.put("role_name", tmpRole.get("name"));
					newTempCheckRuleItem.put("allow_upload_img", allowUploadImg);//前端传参设置
					newTempCheckRuleItem.put("publish", 1);
					newTempCheckRuleItem.put("position", position++);
					newTempCheckRuleItem.put("open_mobile_notice", openMobileNotice);//前端传参设置
					newTempCheckRuleItem.put("open_weixin_notice", openWeixinNotice);//前端传参设置
					newTempCheckRuleItem.put("create_user", this.getLoginUser().getId());
					newTempCheckRuleItem.put("create_time", now);
					newTempCheckRuleItem.put("update_user", this.getLoginUser().getId());
					newTempCheckRuleItem.put("update_time", now);
					int newTempCheckRuleItemId=this.getCommonService().getJdbcDao().addObj(DBTable.checkRuleItem, newTempCheckRuleItem);
					newTempCheckRuleItem.put("id", newTempCheckRuleItemId);
					//和流转操作类似，也使用流转节点变量
					moveRuleItems.add(newTempCheckRuleItem);
				}
				//给当前角色创建一个结尾的审批节点，与当前节点基本一致
				oldCheckRuleItem.remove("id");
				oldCheckRuleItem.put("check_rule_id", newTempCheckRuleId);
				oldCheckRuleItem.put("publish", 1);
				oldCheckRuleItem.put("position", position++);
				oldCheckRuleItem.put("create_user", this.getLoginUser().getId());
				oldCheckRuleItem.put("create_time", now);
				oldCheckRuleItem.put("update_user", this.getLoginUser().getId());
				oldCheckRuleItem.put("update_time", now);
				this.getCommonService().getJdbcDao().addObj(DBTable.checkRuleItem, oldCheckRuleItem);
				//创建后续未完成的流程节点
				if(oldCheckRuleOtherItems!=null) {
					for(int i=0;i<oldCheckRuleOtherItems.size();i++) {
						Map tmpOldCheckRuleItem=(Map)oldCheckRuleOtherItems.get(i);
						tmpOldCheckRuleItem.remove("id");
						tmpOldCheckRuleItem.put("check_rule_id", newTempCheckRuleId);
						tmpOldCheckRuleItem.put("publish", 1);
						tmpOldCheckRuleItem.put("position", position++);
						tmpOldCheckRuleItem.put("create_user", this.getLoginUser().getId());
						tmpOldCheckRuleItem.put("create_time", now);
						tmpOldCheckRuleItem.put("update_user", this.getLoginUser().getId());
						tmpOldCheckRuleItem.put("update_time", now);
						this.getCommonService().getJdbcDao().addObj(DBTable.checkRuleItem, tmpOldCheckRuleItem);
					}
				}	
			}
			//开始审批处理===============================================================
			
			//变更审核记录的审核状态、审核意见等字段
			Map checkRecordEditData=new HashMap();
			checkRecordEditData.put("id", id);
			checkRecordEditData.put("check_status", check_status);
			checkRecordEditData.put("check_user_id", loginUser.getId());
			checkRecordEditData.put("check_user_name", loginUser.getName());
			checkRecordEditData.put("check_description", check_description);
			checkRecordEditData.put("check_time", now);
			this.getCommonService().getJdbcDao().updateObj(DBTable.checkRecord, checkRecordEditData, "id");
			
			if(check_status.equals("1") || check_status.equals("4")) {//审批通过或批注
				Map thisCheckRuleItem=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRuleItem+" where id=?", new Object[] {thisCheckRecord.get("check_rule_item_id")});
				Map otherAsynCheckRecord=null;
				
				//如果是并行节点，查找是否具备同行未完成审批记录
				if(thisCheckRecord.get("check_rule_item_asyn").toString().equals("1")) {
					//同一个审批数据，未完成，并且也为同步审批
					otherAsynCheckRecord=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.checkRecord+" where data_type=? and data_id=? and check_rule_item_asyn=1 and id!=? and check_status=0 and del_flag=0 limit 0,1", new Object[] {thisCheckRecord.get("data_type"),thisCheckRecord.get("data_id"),id});
				}
				
				//如果存在并行节点
				
				//查找有无下一级审批节点
				//Map nextCheckRuleItem=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRuleItem+" where check_rule_id=? and position>? and id!=? and publish=1 and del_flag=0 limit 0,1", new Object[] {thisCheckRuleItem.get("check_rule_id"),thisCheckRuleItem.get("position"),thisCheckRuleItem.get("id")});
				List nextCheckRuleItems=this.getDataHistoryService().getNextCheckRuleItems(Integer.parseInt(thisCheckRuleItem.get("check_rule_id").toString()), thisCheckRuleItem);
				
				
				if(otherAsynCheckRecord!=null) {
					//如果存在未处理的并行审批，不需要执行操作
				}else if(nextCheckRuleItems.size()>0) {//如果下级节点有则创建下一级审批
					for(int i=0;i<nextCheckRuleItems.size();i++) {
						Map nextCheckRuleItem=(Map)nextCheckRuleItems.get(i);
						//增加审批申请
						Map checkRecord=new HashMap();
						checkRecord.put("check_rule_id", thisCheckRecord.get("check_rule_id"));
						checkRecord.put("check_rule_name", thisCheckRecord.get("check_rule_name"));
						checkRecord.put("check_rule_item_id", nextCheckRuleItem.get("id"));
						checkRecord.put("check_rule_item_asyn", nextCheckRuleItem.get("asyn"));
						checkRecord.put("check_org_id", nextCheckRuleItem.get("org_id"));
						checkRecord.put("check_org_name", nextCheckRuleItem.get("org_name"));
						checkRecord.put("check_role_id", nextCheckRuleItem.get("role_id"));
						checkRecord.put("check_role_name", nextCheckRuleItem.get("role_name"));
						checkRecord.put("data_type", thisCheckRecord.get("data_type"));
						checkRecord.put("data_id", thisCheckRecord.get("data_id"));
						checkRecord.put("data_title", thisCheckRecord.get("data_title"));
						checkRecord.put("data_history_id", thisCheckRecord.get("data_history_id"));
						checkRecord.put("submit_site_id", thisCheckRecord.get("submit_site_id"));
						checkRecord.put("submit_site_name", thisCheckRecord.get("submit_site_name"));
						checkRecord.put("submit_menu_id", thisCheckRecord.get("submit_menu_id"));
						checkRecord.put("submit_menu_name", thisCheckRecord.get("submit_menu_name"));
						checkRecord.put("submit_user_id", thisCheckRecord.get("submit_user_id"));
						checkRecord.put("submit_user_name", thisCheckRecord.get("submit_user_name"));
						checkRecord.put("submit_org_id", thisCheckRecord.get("submit_org_id"));
						checkRecord.put("submit_org_name", thisCheckRecord.get("submit_org_name"));
						checkRecord.put("submit_description", thisCheckRecord.get("submit_description"));
						checkRecord.put("submit_time", thisCheckRecord.get("submit_time"));
						checkRecord.put("create_time", now);

						//this.getCommonService().getJdbcDao().addObj(DBTable.checkRecord, checkRecord);
						//统一的保存审批方法，用于发送通知等
						this.getDataHistoryService().saveCheckRecord(checkRecord);
					}
					
				}else {//如果没有则变更数据版本的审批状态为已通过、更新数据版本及审批状态
					//变更数据版本的审批状态为已通过
					Map dataHistoryEditData=new HashMap();
					dataHistoryEditData.put("id", thisCheckRecord.get("data_history_id"));
					//dataHistoryEditData.put("check_status", check_status);
					dataHistoryEditData.put("check_status", 1);//通过或批注，体现在版本表中都是已审核状态
					dataHistoryEditData.put("check_description", check_description);
					this.getCommonService().getJdbcDao().updateObj(DBTable.dataHistory, dataHistoryEditData, "id");
					
					//获取要更新的数据版本
					Map dataHistory=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.dataHistory+" where id=?", new Object[] {thisCheckRecord.get("data_history_id")});
					if(dataHistory!=null && dataHistory.get("params")!=null && !dataHistory.get("params").equals("")) {
						//更新数据表的数据字段、版本、审核状态
						Map dataEditData=JSON.parseObject(dataHistory.get("params").toString(),Map.class);
						dataEditData.put("id", thisCheckRecord.get("data_id"));
						//dataEditData.put("check_status", check_status);
						dataEditData.put("check_status", 1);//通过或批注，体现在业务表中都是已审核状态
						dataEditData.put("data_history_id", thisCheckRecord.get("data_history_id"));
						//this.getCommonService().getJdbcDao().updateObj(thisCheckRecord.get("data_type").toString(), dataEditData, "id");
						//调用统一的数据保存方法
						this.getDataHistoryService().saveSourceData(thisCheckRecord.get("data_type").toString(), dataEditData);	
					}
					
					//审批通过后各模块的后续操作
					if(thisCheckRecord.get("data_type").toString().equals(DBTable.news)) { //更新微信的素材数据
						this.treadTasks.startUpdateWeixinNewsSource(new Integer(thisCheckRecord.get("data_id")+""), false);
					}else if(thisCheckRecord.get("data_type").toString().equals(DBTable.appResource)) {//素材图片加入到图片库
						//将之前版本的图片设置为失效
						this.getCommonService().getJdbcDao().updateSql("update "+DBTable.file+" set useable=0 where data_type=? and data_id=? and useable=1", new Object[] {thisCheckRecord.get("data_type"),thisCheckRecord.get("data_id")});
						//将当前版本图片设置为有效
						this.getCommonService().getJdbcDao().updateSql("update "+DBTable.file+" set useable=1 where data_history_id=? and useable=0", new Object[] {thisCheckRecord.get("data_history_id")});
					}
					
					//发送审核通过通知
					this.getDataHistoryService().checkResultNotice(thisCheckRecord, true);
				}
			}else if(check_status.equals("2")) {//审批未通过
				//变更数据版本的审批状态为未通过
				Map dataHistoryEditData=new HashMap();
				dataHistoryEditData.put("id", thisCheckRecord.get("data_history_id"));
				dataHistoryEditData.put("check_status", check_status);
				dataHistoryEditData.put("check_description", check_description);
				this.getCommonService().getJdbcDao().updateObj(DBTable.dataHistory, dataHistoryEditData, "id");
				
				
				//发送审核失败通知
				this.getDataHistoryService().checkResultNotice(thisCheckRecord, false);
				
			}else if(check_status.equals("3")) {//审批作废
				//变更数据版本的审批状态为已作废
				Map dataHistoryEditData=new HashMap();
				dataHistoryEditData.put("id", thisCheckRecord.get("data_history_id"));
				dataHistoryEditData.put("check_status", check_status);
				dataHistoryEditData.put("check_description", check_description);
				this.getCommonService().getJdbcDao().updateObj(DBTable.dataHistory, dataHistoryEditData, "id");
				
				
				//找到最后一次审批成功的数据版本，把后面的全都作废，找不到则全部作废
				int lastPublishHistoryId=0;
				Map lastPublishHistory=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.dataHistory+" where check_status=1 and data_id=? and data_type=? order by id desc limit 0,1", new Object[] {thisCheckRecord.get("data_id"),thisCheckRecord.get("data_type")});
				if(lastPublishHistory!=null) {
					lastPublishHistoryId=Integer.parseInt(lastPublishHistory.get("id").toString());
				}
				this.getCommonService().getJdbcDao().updateSql("update "+DBTable.dataHistory+" set check_status=? where data_id=? and data_type=? and id>?", new Object[] {check_status,thisCheckRecord.get("data_id"),thisCheckRecord.get("data_type"),lastPublishHistoryId});

				//发送审核失败通知
				this.getDataHistoryService().checkResultNotice(thisCheckRecord, false);
				
				
			}else if(check_status.equals("5") || check_status.equals("6")) {//流转及会签的处理在这里是一样的
				for(int i=0;i<moveRuleItems.size();i++) {
					Map moveRuleItem=(Map)moveRuleItems.get(i);
					//增加转发审批申请
					Map checkRecord=new HashMap();
					checkRecord.put("check_rule_id", moveRule.get("id"));
					checkRecord.put("check_rule_name", moveRule.get("name"));
					checkRecord.put("check_rule_item_id", moveRuleItem.get("id"));
					checkRecord.put("check_rule_item_asyn", moveRuleItem.get("asyn"));
					checkRecord.put("check_org_id", moveRuleItem.get("org_id"));
					checkRecord.put("check_org_name", moveRuleItem.get("org_name"));
					checkRecord.put("check_role_id", moveRuleItem.get("role_id"));
					checkRecord.put("check_role_name", moveRuleItem.get("role_name"));
					checkRecord.put("data_type", thisCheckRecord.get("data_type"));
					checkRecord.put("data_id", thisCheckRecord.get("data_id"));
					checkRecord.put("data_title", thisCheckRecord.get("data_title"));
					checkRecord.put("data_history_id", thisCheckRecord.get("data_history_id"));
					checkRecord.put("submit_site_id", thisCheckRecord.get("submit_site_id"));
					checkRecord.put("submit_site_name", thisCheckRecord.get("submit_site_name"));
					checkRecord.put("submit_menu_id", thisCheckRecord.get("submit_menu_id"));
					checkRecord.put("submit_menu_name", thisCheckRecord.get("submit_menu_name"));
					checkRecord.put("submit_user_id", thisCheckRecord.get("submit_user_id"));
					checkRecord.put("submit_user_name", thisCheckRecord.get("submit_user_name"));
					checkRecord.put("submit_org_id", thisCheckRecord.get("submit_org_id"));
					checkRecord.put("submit_org_name", thisCheckRecord.get("submit_org_name"));
					checkRecord.put("submit_description", thisCheckRecord.get("submit_description"));
					checkRecord.put("submit_time", thisCheckRecord.get("submit_time"));
					checkRecord.put("create_time", now);
					//this.getCommonService().getJdbcDao().addObj(DBTable.checkRecord, checkRecord);
					this.getDataHistoryService().saveCheckRecord(checkRecord);
				}
				
				
			}else {
				Map result=new HashMap();
				result.put("result", 0);
				result.put("msg", "审核参数有误");
				return WebUtil.resultString(result,request);
			}
			
			
			
			
			Map result=new HashMap();
			result.put("result", 1);
			result.put("msg", "操作成功");
			return WebUtil.resultString(result,request);
			
			
		}else {
			Map result=new HashMap();
			result.put("result", 0);
			result.put("msg", "参数有误");
			return WebUtil.resultString(result,request);
		}
		
	}
	
	@RequestMapping(value="/dataCheckRuleAndRecord",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String dataCheckRuleAndRecord(HttpServletRequest request){
		Map data=new HashMap();

		if(request.getParameter("data_history_id")!=null && !request.getParameter("data_history_id").equals("")){
			List dataList=new ArrayList();
			
			//20211107补充功能，如果是最新的版本数据，顺便查询出之前的历史审批记录=================================
			//查询数据版本记录，获取数据ID
			Map dataHistory=this.getCommonService().getJdbcDao().queryRow("select id,data_type,module_name,data_id from "+DBTable.dataHistory+" where id=?", new Object[] {request.getParameter("data_history_id")});
			int dataHistoryId=Integer.parseInt(dataHistory.get("id").toString());
			if(dataHistory!=null) {
				//查询历史版本记录（不包括当前版本）
				List otherDataHistorys=this.getCommonService().getJdbcDao().querySql("select id,data_type,module_name,data_id from "+DBTable.dataHistory+" where data_type=? and data_id=? and module_name=? and id!=? order by id asc limit 0,1000", new Object[] {dataHistory.get("data_type"),dataHistory.get("data_id"),dataHistory.get("module_name"),dataHistory.get("id")});
				//判断当前版本是否是最新版本
				if(otherDataHistorys!=null && otherDataHistorys.size()>0) {
					Map lastDataHistory=(Map)otherDataHistorys.get(otherDataHistorys.size()-1);
					int lastDataHistoryId=Integer.parseInt(lastDataHistory.get("id").toString());
					//如果当前是最新版本
					if(lastDataHistoryId<dataHistoryId) {
						//查询历史审批记录（包括没有操作人自动作废的记录）
						for(int i=0;i<otherDataHistorys.size();i++) {
							Map tmpDataHistory=(Map)otherDataHistorys.get(i);
							String sql="select i.check_rule_id,i.id as rule_item_id,i.org_id,i.org_name,i.role_name,i.position,r.check_user_name,r.check_status,r.check_description,r.check_time,r.id as check_record_id " + 
									"from cms_check_record r join cms_check_rule_item i on r.check_rule_item_id=i.id " + 
									"where r.data_history_id=? and r.del_flag=0 order by r.id asc";
							List tmpdataList=this.getCommonService().getJdbcDao().querySql(sql, new Object[] {tmpDataHistory.get("id")});
							if(tmpdataList!=null && tmpdataList.size()>0) {
								dataList.addAll(tmpdataList);
							}
						}
					}
				}
				
				
			}
			//end===============================
			
			
			//查询审批记录
			String sql="select i.check_rule_id,i.id as rule_item_id,i.org_id,i.org_name,i.role_name,i.position,r.check_user_name,r.check_status,r.check_description,r.check_time,r.id as check_record_id " + 
					"from cms_check_record r join cms_check_rule_item i on r.check_rule_item_id=i.id " + 
					"where r.data_history_id=? and r.del_flag=0 order by r.id asc";
			List tmpdataList=this.getCommonService().getJdbcDao().querySql(sql, new Object[] {request.getParameter("data_history_id")});
			dataList.addAll(tmpdataList);
			//获取第一条，查询是否存在跳过的节点,这个功能应该已经没用了，目前不存在跳过的情况了
			/*if(dataList!=null && dataList.size()>0) {
				Map firstCheckRecord=(Map)dataList.get(0);
				String tmpsql="select i.check_rule_id,i.id as rule_item_id,i.org_name,i.role_name,i.position,-1 as check_status from cms_check_rule_item i " + 
						"where i.check_rule_id=? and i.publish=1 and i.id!=? and i.position<=? and i.del_flag=0 order by i.position asc,i.id asc";
				List tmpdataList=this.getCommonService().getJdbcDao().querySql(tmpsql, new Object[] {firstCheckRecord.get("check_rule_id"),firstCheckRecord.get("rule_item_id"),firstCheckRecord.get("position")});
				if(tmpdataList!=null && tmpdataList.size()>0) {
					tmpdataList.addAll(dataList);
					dataList=tmpdataList;
				}
			}*/
			
			//获取最后一条，查询是否还存在后续待审批节点
			if(dataList!=null && dataList.size()>0) {
				Map lastCheckRecord=(Map)dataList.get(dataList.size()-1);
				String tmpsql="select i.check_rule_id,i.id as rule_item_id,i.org_id,i.org_name,i.role_name,i.position from cms_check_rule_item i " + 
						"where i.check_rule_id=? and i.publish=1 and i.id!=? and i.position>=? and i.del_flag=0 order by i.position asc,i.id asc";
				tmpdataList=this.getCommonService().getJdbcDao().querySql(tmpsql, new Object[] {lastCheckRecord.get("check_rule_id"),lastCheckRecord.get("rule_item_id"),lastCheckRecord.get("position")});
				if(tmpdataList!=null && tmpdataList.size()>0) {
					dataList.addAll(tmpdataList);
				}
			}
			
			
			if(dataList!=null) {
				//设置默认审批状态，默认跳过的显示为"无需审批"，后面未开始的节点显示为待审批
				boolean hasRecord=false;
				for(int i=0;i<dataList.size();i++) {
					Map row=(Map)dataList.get(i);
					
					
					
					if(row.get("check_status")!=null) {
						//如果不是待审批和已作废，查询图片附件
						if(!row.get("check_status").toString().equals("0") && !row.get("check_status").toString().equals("3")) {
							List files=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.checkRecordFile+" where type=1 and del_flag=0 and check_record_id=? order by id asc limit 0,100", new Object[] {row.get("check_record_id")});
							
							if(files!=null && files.size()>0) {
								
								for(int j=0;j<files.size();j++) {
									Map img=(Map)files.get(j);
									if(img.get("file")!=null) {
										img.put("file", Config.getFileUrl(img.get("file").toString()));
									}
								}
								
								row.put("files", files);
							}
						
						}
						
						
						
						hasRecord=true;
					}else {
						if(!hasRecord) {
							row.put("check_status", -1);//无需审批
						}else{
							row.put("check_status", -2);//未开始
							
						}
					}
					
					
				}
			}
			
			//20211107增加过滤，下级无法查看上级的批注功能===================================
			if(dataList!=null && dataList.size()>0) {
				
				//log.info(this.getLoginUser().getSubOrgIds());
				
				Iterator<Map> it = dataList.iterator();
				while(it.hasNext()){
				    Map row = it.next();
				    
				    if(row.get("check_status").toString().equals("4")){
				    	//log.info("(^|,)"+row.get("org_id")+"($|,)");
				    	Pattern p=Pattern.compile("(^|.+,)"+row.get("org_id")+"($|,.+)");//第二个参数代表不区分大小写,可以同时使用多种，例如 Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
				    	Matcher m=p.matcher(this.getLoginUser().getSubOrgIds());
				    	boolean result=m.matches();
				    	if(!result) {
				    		it.remove();
				    	} 
				    }
				}
			}
			
			//end============================================================================
			
			
			if(dataList!=null && dataList.size()>0) {
				data.put("data", dataList.toArray());
				data.put("itemsCount", dataList.size());
				return WebUtil.resultString(data,request);
			}
			
			/*//查询已有的审批记录，如果存在说明需要审批
			Map thisCheckRecord=this.getCommonService().getJdbcDao().queryRow("select check_rule_id from "+DBTable.checkRecord+" where data_history_id=? order by id asc limit 0,1", new Object[] {request.getParameter("data_history_id")});
			if(thisCheckRecord!=null) {
				int check_rule_id=Integer.parseInt(thisCheckRecord.get("check_rule_id").toString());
				//查询审批规则明细 
				String sql="select i.org_name,i.role_name,r.check_user_name,r.check_status,r.check_description,r.check_time from cms_check_rule_item i " + 
						"left join cms_check_record r on r.check_rule_item_id=i.id and r.data_history_id=? " + 
						"where i.check_rule_id=? and i.publish=1 and i.del_flag=0 order by i.position asc,i.id asc";
				List dataList=this.getCommonService().getJdbcDao().querySql(sql, new Object[] {request.getParameter("data_history_id"),check_rule_id});
				if(dataList!=null) {
					//设置默认审批状态，默认跳过的显示为"无需审批"，后面未开始的节点显示为待审批
					boolean hasRecord=false;
					for(int i=0;i<dataList.size();i++) {
						Map row=(Map)dataList.get(i);
						
						if(row.get("check_status")!=null) {
							hasRecord=true;
						}else {
							if(!hasRecord) {
								row.put("check_status", -1);
							}else{
								row.put("check_status", 0);
							}
						}
						
						
					}
				}
				
				if(dataList!=null && dataList.size()>0) {
					data.put("data", dataList.toArray());
					data.put("itemsCount", dataList.size());
					return WebUtil.resultString(data,request);
				}
			}*/
			
		}
		data.put("data", new Object[]{});
		data.put("itemsCount", 0);
		return WebUtil.resultString(data,request);
	}
	

	
	//根据审批记录获取可流转的审批规则
	@RequestMapping(value="/getMoveCheckRuleList",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getMoveCheckRuleList(HttpServletRequest request){
		//审批记录ID
		String checkRecordId=request.getParameter("id");
		//查询审批内容
		Map thisCheckRecord=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRecord+" where id=? and check_status=0 and del_flag=0", new Object[] {checkRecordId});
		
		if(thisCheckRecord==null) {
			return WebUtil.resultString(null,request);
		}
		
		
		Map checkRuleItem=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.checkRuleItem+" where id=?", new Object[] {thisCheckRecord.get("check_rule_item_id")});
		if(checkRuleItem==null) {
			return WebUtil.resultString(null,request);
		}
		
		String ids="0";
		if(checkRuleItem.get("move_rules")!=null && !checkRuleItem.get("move_rules").toString().equals("")) {
			ids=checkRuleItem.get("move_rules").toString();
		}
		
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="where del_flag=0 and id in("+ids+")";
		
		
		
		
		//搜索参数
		if(request.getParameter("name")!=null && !request.getParameter("name").toString().trim().equals("")){
			where+=" and name like ? ";
			whereParamList.add("%"+request.getParameter("name")+"%");
		}
		if(request.getParameter("org_name")!=null && !request.getParameter("org_name").toString().trim().equals("")){
			where+=" and org_name like ? ";
			whereParamList.add("%"+request.getParameter("org_name")+"%");
		}
		
		
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		//排序参数 
		String sortField="position";
		String sortOrder="asc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.checkRule+" "+where+" order by "+sortField+" "+sortOrder+",create_time desc,id desc limit ?,?", whereParamList.toArray());
		
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				
				//节点数
				Map ruleItemCount=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.checkRuleItem+" where check_rule_id=? and del_flag=0",new Object[] {row.get("id")});
				int nodeNums=0;
				if(ruleItemCount.get("count_num")!=null){
					nodeNums=new Integer(ruleItemCount.get("count_num").toString()).intValue();
				}
				row.put("nodeNums",nodeNums);
				
			}
		}
		
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.checkRule+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		return WebUtil.resultString(data,request);
	}
	
	//申请预览地址
	@RequestMapping(value="/applyPreviewQrcode/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String applyPreviewQrcode(@PathVariable("id") String dataHistoryId,HttpServletRequest request){

		
		Map dataHistory=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.dataHistory+" where id=? ", new Object[] {dataHistoryId});
		String link=null;
		try {
			String webUrl="/dataHistory/preview/"+dataHistoryId;
			String action="/adminWeixin/login?action="+java.net.URLEncoder.encode(webUrl,"UTF-8");
			link = Config.getValue("app.adminapiDomain")+"/adminWeixin/getBaseCode?action="+ java.net.URLEncoder.encode(action,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(),e);
		}
		//如果数据有误，输出错误提示
		Map data=new HashMap();
		data.put("result", 1);
		data.put("link",link);
		return WebUtil.resultString(data,request);
		
	}
	
	//手机扫码预览内容
	@RequestMapping(value="/preview/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String preview(@PathVariable("id") String dataHistoryId,HttpServletRequest request){
		if(this.getLoginUser()==null) {
			//如果数据有误，输出错误提示
			Map data=new HashMap();
			data.put("result", 0);
			data.put("name", "操作失败");
			data.put("desc", "没有访问权限，请重新扫描二维码");
			return this.templateResult("mobileResult", data);
		}
		
		Map dataHistory=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.dataHistory+" where id=? ", new Object[] {dataHistoryId});
		//查询数据，获取最新的数据版本
		if(dataHistory!=null) {
			Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+dataHistory.get("data_type")+" where id=? and del_flag=0", new Object[] {dataHistory.get("data_id")});
			Map lastHistory=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.dataHistory+" where data_type=? and data_id=? order by id desc limit 0,1", new Object[] {dataHistory.get("data_type"),dataHistory.get("data_id")});
			if(lastHistory!=null) {
				if(lastHistory.get("params")!=null) {
					//使用最新的版本字段替换掉当前主表字段进行显示
					Map param=JSON.parseObject(lastHistory.get("params").toString(),Map.class);
					if(param!=null) {
						for(Object key : param.keySet()) {
							if(param.get(key)!=null) {
								record.put(key, param.get(key));
							}
						}
					}
				}
			}
			
			//预览时替换掉editmark标记
			if(record.get("content")!=null) {
				record.put("content", this.getDataHistoryService().removeEditMark(record.get("content").toString()));
			}
			
			//展示并输出模板
			Map data=new HashMap();
			data.put("data", record);
			return this.templateResult("newsPreview", data);
			
		}
		
		//如果数据有误，输出错误提示
		Map data=new HashMap();
		data.put("result", 0);
		data.put("name", "操作失败");
		data.put("desc", "您浏览的内容不存在或已过期");
		return this.templateResult("mobileResult", data);
		
	}
	
	//通过微信消息预览内容（需要调用微信素材预览接口）
	/*@RequestMapping(value="/weixinMsgPreview/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String weixinMsgPreview(@PathVariable("id") String dataHistoryId,HttpServletRequest request){
		
		Map dataHistory=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.dataHistory+" where id=? ", new Object[] {dataHistoryId});
		
		//数据以版本记录类型同步至公众号素材库
		//appWeixinSourceService.addWeiXinPreviewSource(dataHistoryId);
		
		//如果数据有误，输出错误提示
		Map data=new HashMap();
		data.put("result", 0);
		data.put("name", "操作失败");
		data.put("desc", "您浏览的内容不存在或已过期");
		return this.templateResult("mobileResult", data);
		
		
	}*/
	
}
